package com.linyx.simpleboot.service;
import java.io.InputStream;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class XmlTools {
// public static void main(String[] args) {
//
//  String url = "org/tel/sys/entity/telSql.xml";
//  String sql= XmlTools.parseXmlData(url, "sss");
//  System.out.println(sql);
// }

 /**
  * @method getParseXmlDocument
  * @param parseXmlPath
  *            待解析的xml文件路径,该路径必须要在classpath中能找到
  * @throws DocumentException
  * @方法描述：获取指定xml文档的对象document
  */
 @SuppressWarnings("static-access")
 public static Document getParseXmlDocument(String parseXmlPath) {
  if (parseXmlPath == null) {
   return null;
  }

  SAXReader reader = new SAXReader();
  Document document = null;
  try {
   ClassLoader classLoader = XmlTools.class.getClassLoader();
   InputStream inputStream = classLoader
     .getResourceAsStream(parseXmlPath);
   // InputStream inputStream = XmlTools.class.getResourceAsStream(parseXmlPath);
   document = reader.read(inputStream);
   return document;
  } catch (DocumentException de) {
   System.out.println("读取classpath下的xml文档路径发生异常");
   return null;
  }
 }

 public static String parseXmlData(String parseXmlFile, String sqlName) {
  // 将xml文档转换为Document对象
  Document document = getParseXmlDocument(parseXmlFile);
  Element root = document.getRootElement();
  String sqlStr = "";
  for (Iterator<?> it = root.elementIterator(); it.hasNext();) {
   Element essp = (Element) it.next();
   String value = essp.getName();
   System.out.println(value);
   if ("sql-query".equals(value)) {
    String name = essp.attributeValue("name");
    System.out.print(name + "\n");
    if (sqlName.trim().equals(name)) {
     sqlStr = essp.getText();
     break;
    }
   }
  }
  return sqlStr;
 }
}
 